package com.dongbo.recorder.screenrecord.ui.fragment;

import static android.app.Activity.RESULT_OK;
import static android.content.Context.BIND_AUTO_CREATE;
import static android.content.Context.MEDIA_PROJECTION_SERVICE;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.GradientDrawable;
import android.hardware.display.DisplayManager;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dongbo.recorder.screenrecord.utils.eventbus.EventBusUtils;
import com.dongbo.recorder.screenrecord.utils.eventbus.EventMessage;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.huxq17.floatball.libarary.FloatBallManager;
import com.huxq17.floatball.libarary.floatball.FloatBallCfg;
import com.huxq17.floatball.libarary.menu.FloatMenuCfg;
import com.huxq17.floatball.libarary.menu.MenuItem;
import com.huxq17.floatball.libarary.utils.DensityUtil;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.umeng.analytics.MobclickAgent;
import com.yhao.floatwindow.FloatWindow;
import com.yhao.floatwindow.MoveType;
import com.yhao.floatwindow.PermissionListener;
import com.yhao.floatwindow.ViewStateListener;
import com.dongbo.recorder.screenrecord.AppLpds;
import com.dongbo.recorder.screenrecord.R;
import com.dongbo.recorder.screenrecord.base.BaseFragment;
import com.dongbo.recorder.screenrecord.contents.Contents;
import com.dongbo.recorder.screenrecord.dialog.CountTimePop;
import com.dongbo.recorder.screenrecord.service.RecordService;
import com.dongbo.recorder.screenrecord.ui.activity.MainActivity;
import com.dongbo.recorder.screenrecord.utils.DateUtils;
import com.dongbo.recorder.screenrecord.utils.FileUtils;
import com.dongbo.recorder.screenrecord.utils.PermissionUtil;
import com.dongbo.recorder.screenrecord.utils.SystemUtils;
import com.dongbo.recorder.screenrecord.utils.rom.FloatPermissionManager;
import com.dongbo.recorder.screenrecord.widget.CameraView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.autosize.utils.AutoSizeUtils;

/**
 * @author GuoZi
 * @date :2020/5/5 13:47
 * @description:
 */
public class HomeFragment extends BaseFragment {
    @BindView(R.id.home_definition)
    SegmentTabLayout homeDefinition;
    @BindView(R.id.home_voice)
    SegmentTabLayout homeVoice;
    @BindView(R.id.home_suspension)
    SegmentTabLayout homeSuspension;
    @BindView(R.id.home_direction)
    LinearLayout homeDirection;
    @BindView(R.id.home_direction_iv)
    ImageView homeDirectionIv;
    @BindView(R.id.home_direction_tv)
    TextView homeDirectionTv;
    @BindView(R.id.home_recordtime)
    TextView homeRecordtime;
    @BindView(R.id.home_record)
    ImageView homeRecord;
    @BindView(R.id.root)
    View root;

    private String[] definitions = {"标清", "高清", "超清"};
    private String[] voices = {"关闭声音", "开启声音"};
    private String[] suspensions = {"关闭浮窗", "开启浮窗"};

    //录屏相关
    private static final int RECORD_REQUEST_CODE = 101;
    private MediaProjectionManager projectionManager;
    private MediaProjection mediaProjection;
    private RecordService recordService;

    private FloatPermissionManager mFloatPermissionManager;

    MainActivity mainActivity;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {

        GradientDrawable gradientDrawable = new GradientDrawable(
                GradientDrawable.Orientation.TOP_BOTTOM,
                new int[]{Color.parseColor("#5298f0"), Color.parseColor("#F5F7FB")}
        );
        root.setBackground(gradientDrawable);

    }

    @Override
    protected void initData() {
        mainActivity = (MainActivity) getActivity();
        homeDefinition.setTabData(definitions);
        homeVoice.setTabData(voices);
        homeSuspension.setTabData(suspensions);
        homeDefinition.setCurrentTab(AppLpds.getMySp().getDefinitiont());
        homeVoice.setCurrentTab(AppLpds.getMySp().getVoice());
        homeSuspension.setCurrentTab(AppLpds.getMySp().getSuspension());
        changeDirection();
        projectionManager = (MediaProjectionManager) getActivity().getSystemService(MEDIA_PROJECTION_SERVICE);
        //开启后台服务
        Intent intent = new Intent(getActivity(), RecordService.class);
        getActivity().bindService(intent, connection, BIND_AUTO_CREATE);
        //当悬浮球存在的时候 重置
        if (AppLpds.mFloatballManager != null) {
            AppLpds.mFloatballManager.hide();
            AppLpds.mFloatballManager = null;
        }
        initBall();
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initListener() {
        //清晰度
        homeDefinition.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                AppLpds.getMySp().setDefinition(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        //声音
        homeVoice.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                AppLpds.getMySp().setVoice(position);
//                Log.d("声音---->", AppLpds.getMySp().getVoice() + "");
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        //浮窗
        homeSuspension.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
//                showCamera();
                if (position == 0) {
                    AppLpds.mFloatballManager.hide();
                } else {
                    AppLpds.mFloatballManager.show();
                }
                AppLpds.getMySp().setSuspension(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }

    @OnClick({R.id.home_direction, R.id.home_record})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.home_direction:
                AppLpds.getMySp().setDirection(AppLpds.getMySp().getDirection() == 0 ? 1 : 0);
                changeDirection();
                break;
            case R.id.home_record:
                if (recordService.isRunning()) {
                    stopRecord();
                } else {
                    checkRecordPermissions();
                }
                break;
        }
    }

    //切换横竖屏
    private void changeDirection() {
        if (AppLpds.getMySp().getDirection() == 1) {
            homeDirectionIv.setImageResource(R.mipmap.index_screen_h_icon);
            homeDirectionTv.setText(R.string.text_verticalscreen);
        } else {
            homeDirectionIv.setImageResource(R.mipmap.index_screen_v_icon);
            homeDirectionTv.setText(R.string.text_horizontalscreen);
        }
    }

    //录屏服务
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            DisplayMetrics metrics = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
            RecordService.RecordBinder binder = (RecordService.RecordBinder) service;
            recordService = binder.getRecordService();
//            Log.d("story", metrics.widthPixels + "==" + metrics.heightPixels + "==" + metrics.densityDpi);
            recordService.setConfig(1080, 1920, metrics.densityDpi);
            homeRecord.setEnabled(true);
            homeRecord.setImageResource(recordService.isRunning() ? R.mipmap.index_stop_btn : R.mipmap.index_start_btn);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("gstroy", requestCode + "=" + resultCode);
        //调用录屏 确认回调
        if (requestCode == RECORD_REQUEST_CODE && resultCode == RESULT_OK) {
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(false)
                    .dismissOnTouchOutside(false)
                    .asCustom(new CountTimePop(getActivity(), this, resultCode, data))
                    .show();

        } else if (requestCode == 10086 && resultCode == RESULT_OK) {
            savePic(resultCode, data);
        }
    }

    /**
     * 开始录屏
     *
     * @param resultCode
     * @param data
     */
    public void startGoRecord(int resultCode, Intent data) {
        //app进入后台
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //启动录屏服务
                recordService.createNotificationChannel();
                mediaProjection = projectionManager.getMediaProjection(resultCode, data);
                recordService.setMediaProject(mediaProjection);
                recordService.startRecord();
                homeRecord.setImageResource(R.mipmap.index_stop_btn);
                //重置图标
                addFloatMenuItem();
            }
        }, 1000);

    }

    /**
     * 结束录屏
     */
    public void stopRecord() {
        recordService.stopRecord();
        homeRecord.setImageResource(R.mipmap.index_start_btn);
        EventBusUtils.post(new EventMessage<>(Contents.EventType.TAG_RECORD_SUCCESS, true));
        homeRecordtime.setText(DateUtils.longToDate(0));
        showToast("录屏已保存，可前往视频库查看");
        //重置图标
        addFloatMenuItem();
        //如果摄像头开启就关闭
        if (FloatWindow.get("camera") != null) {
            FloatWindow.destroy("camera");
        }
        //如果app不在前台运行 就返回页面
        if (!SystemUtils.isRunForeground()) {
            SystemUtils.RunForeground(getActivity(), MainActivity.class);
        }
    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    /**
     * 接收到推送的事件
     *
     * @param event 事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPushReceiveEvent(final EventMessage event) {
        if (event.getCode() == Contents.EventType.TAG_RECORD_DATE) {
            long time = (long) event.getData();
            homeRecordtime.setText(DateUtils.longToDate(time));
        }
    }

    /**
     * 保存截图文件
     *
     * @param resultCode
     * @param data
     */
    //只保存一次
    int saveNum = 0;

    public void savePic(int resultCode, Intent data) {
        saveNum = 0;
        recordService.createNotificationChannel();
        WindowManager windowManager = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        int width = 0;
        int height = 0;
        int dpi = 0;
        if (windowManager != null) {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            windowManager.getDefaultDisplay().getMetrics(displayMetrics);
            width = displayMetrics.widthPixels;
            height = displayMetrics.heightPixels;
            dpi = displayMetrics.densityDpi;
        }
        MediaProjection mediaProjection = projectionManager.getMediaProjection(resultCode, data);
        @SuppressLint({"Range", "WrongConstant"})
        ImageReader imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 3);
        mediaProjection.createVirtualDisplay("screen_shot",
                width, height, dpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                imageReader.getSurface(), null, null);
        imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(ImageReader imageReader) {
                Image image = imageReader.acquireNextImage();//获取下一帧截屏，这里可以控制你是否要单个或者直接录屏
                saveNum++;
                //取第五张
                if (saveNum == 5) {
                    int width = image.getWidth();
                    int height = image.getHeight();
                    final Image.Plane[] planes = image.getPlanes();
                    final ByteBuffer buffer = planes[0].getBuffer();
                    int pixelStride = planes[0].getPixelStride();
                    int rowStride = planes[0].getRowStride();
                    int rowPadding = rowStride - pixelStride * width;
                    Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
                    bitmap.copyPixelsFromBuffer(buffer);
                    if (bitmap != null) {
                        try {
                            // 获取内置SD卡路径
                            String sdCardPath = FileUtils.getScreenshotFile();
                            // 图片文件路径
                            String filePath = sdCardPath + System.currentTimeMillis() + ".jpg";
                            File file = new File(filePath);
                            FileOutputStream fos = new FileOutputStream(file);
                            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                            fos.flush();
                            fos.close();
                            recordService.clearNotification();
                            EventBusUtils.post(new EventMessage<>(Contents.EventType.TAG_SHOT_SUCCESS, true));
                            showToast("截图已保存，请前往视频库查看");
                        } catch (Exception e) {
                        }
                    } else {
                    }
                }
                image.close();
            }
        }, null);
    }


    @SuppressLint("CheckResult")
    private void checkRecordPermissions() {
        //只显示一次
        final BasePopupView[] xPopup = {null};
        mainActivity.getRxPermissions()
                .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO)
                .subscribe(permission -> {
                    if (permission.granted) {
                        //获取了权限
                        if (permission.name.equals(Manifest.permission.RECORD_AUDIO)) {
                            startActivityForResult(projectionManager.createScreenCaptureIntent(), RECORD_REQUEST_CODE);
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // Denied permission without ask never again
//                        Log.d("gstory", "不再询问");
                    } else {
                        // Denied permission with ask never again
                        // Need to go to the settings
                        if (xPopup[0] == null) {
                            xPopup[0] = new XPopup.Builder(getActivity())
                                    .asConfirm(getResources().getString(R.string.tips),
                                            getResources().getString(R.string.tips_record),
                                            new OnConfirmListener() {
                                                @Override
                                                public void onConfirm() {
                                                    PermissionUtil.gotoPermission(getActivity());
                                                }
                                            })
                                    .setCancelText(getResources().getString(R.string.btn_sure))
                                    .setConfirmText(getResources().getString(R.string.btn_gosetting))
                                    .show();
                        }
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("HomeFragment"); //统计页面("MainScreen"为页面名称，可自定义)
        if (AppLpds.getMySp().getSuspension() == 1) {
            AppLpds.mFloatballManager.show();
        } else {
            AppLpds.mFloatballManager.hide();
        }
    }

    //初始化悬浮球
    private void initBall() {
        int ballSize = DensityUtil.dip2px(getActivity(), 45);
        FloatBallCfg ballCfg = new FloatBallCfg(ballSize,
                getResources().getDrawable(R.mipmap.float_win_btn),
                FloatBallCfg.Gravity.RIGHT_CENTER);
        //设置悬浮球不半隐藏
        ballCfg.setHideHalfLater(false);
        int menuSize = DensityUtil.dip2px(getActivity(), 180);
        int menuItemSize = DensityUtil.dip2px(getActivity(), 40);
        FloatMenuCfg menuCfg = new FloatMenuCfg(menuSize, menuItemSize);
        AppLpds.mFloatballManager = new FloatBallManager(AppLpds.getInstance(), ballCfg, menuCfg);
        addFloatMenuItem();
        setFloatPermission();
    }

    private void setFloatPermission() {
        // 设置悬浮球权限，用于申请悬浮球权限的
        //如果不设置permission，则不会弹出悬浮球
        mFloatPermissionManager = new FloatPermissionManager();
        AppLpds.mFloatballManager.setPermission(new FloatBallManager.IFloatBallPermission() {
            @Override
            public boolean onRequestFloatBallPermission() {
                requestFloatBallPermission(getActivity());
//                Log.v("gstory========>", "daozheli 1");
                return true;
            }

            @Override
            public boolean hasFloatBallPermission(Context context) {
//                Log.v("gstory========>", "daozheli 2");
                return mFloatPermissionManager.checkPermission(context);

            }

            @Override
            public void requestFloatBallPermission(Activity activity) {
//                Log.v("gstory========>", "daozheli 3");
                mFloatPermissionManager.applyPermission(activity);
            }
        });
    }

    private void addFloatMenuItem() {
        //录屏 R.mipmap.float_win_start_icon
        MenuItem startRecrodItem = new MenuItem(getResources().getDrawable(R.mipmap.float_start)) {
            @Override
            public void action() {
                AppLpds.mFloatballManager.closeMenu();
                //如果app不在前台运行 就返回页面
                if (!SystemUtils.isRunForeground()) {
                    SystemUtils.RunForeground(getActivity(), MainActivity.class);
                    //延时1秒
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            checkRecordPermissions();
                        }
                    }, 1000L);
                } else {
                    checkRecordPermissions();
                }
            }
        };
        //停止录屏 R.mipmap.float_win_stop_icon
        MenuItem stopRecrodItem = new MenuItem(getResources().getDrawable(R.mipmap.float_stop)) {
            @Override
            public void action() {
                AppLpds.mFloatballManager.closeMenu();
                stopRecord();
            }
        };
        //截图
//        MenuItem shootItem = new MenuItem(getResources().getDrawable(R.mipmap.float_win_screenshot_icon)) {
//            @Override
//            public void action() {
//                if (recordService.isRunning()) {
//                    showToast("录屏过程中不能截图，请稍后再试");
//                    return;
//                }
//                AppLpds.mFloatballManager.closeMenu();
//                //如果app不在前台运行 就返回页面
//                if (!SystemUtils.isRunForeground()) {
//                    SystemUtils.RunForeground(getActivity(), MainActivity.class);
//                    //延时1秒
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            startActivityForResult(projectionManager.createScreenCaptureIntent(), 10086);
//                        }
//                    }, 1000L);
//                } else {
//                    startActivityForResult(projectionManager.createScreenCaptureIntent(), 10086);
//                }
//            }
//        };
        //返回APP首页
        MenuItem settingItem = new MenuItem(getResources().getDrawable(R.mipmap.float_win_menu_icon)) {
            @Override
            public void action() {
                AppLpds.mFloatballManager.closeMenu();
                if (!SystemUtils.isRunForeground()) {
                    SystemUtils.RunForeground(getActivity(), MainActivity.class);
                }
            }
        };

        //摄像头
        MenuItem cameraItem = new MenuItem(getResources().getDrawable(R.mipmap.float_win_nocamera_icon)) {
            @SuppressLint("CheckResult")
            @Override
            public void action() {
                AppLpds.mFloatballManager.closeMenu();
                //只显示一次
                final BasePopupView[] xPopup = {null};
                mainActivity.getRxPermissions()
                        .requestEach(Manifest.permission.CAMERA)
                        .subscribe(permission -> {
                            if (permission.granted) {
                                //获取了权限
                                showCamera();
                            } else if (permission.shouldShowRequestPermissionRationale) {
                                // Denied permission without ask never again
                                Log.d("gstory", "不再询问");
                            } else {
                                // Denied permission with ask never again
                                // Need to go to the settings
                                if (xPopup[0] == null) {
                                    xPopup[0] = new XPopup.Builder(getActivity())
                                            .asConfirm(getResources().getString(R.string.tips),
                                                    getResources().getString(R.string.tips_record),
                                                    new OnConfirmListener() {
                                                        @Override
                                                        public void onConfirm() {
                                                            PermissionUtil.gotoPermission(getActivity());
                                                        }
                                                    })
                                            .setCancelText(getResources().getString(R.string.btn_sure))
                                            .setConfirmText(getResources().getString(R.string.btn_gosetting))
                                            .show();
                                }
                            }
                        });
            }
        };
        List<MenuItem> items = new ArrayList<>();
        if (recordService == null || !recordService.isRunning()) {
            items.add(startRecrodItem);
//            items.add(shootItem);
            items.add(settingItem);
            items.add(cameraItem);
        } else {
            items.add(stopRecrodItem);
//            items.add(shootItem);
            items.add(settingItem);
            items.add(cameraItem);
        }
        AppLpds.mFloatballManager
                .setMenu(items)
                .buildMenu();
    }

    //显示摄像头
    public void showCamera() {
        String TAG = "gstory";
        if (FloatWindow.get("camera") == null) {
            CameraView mCameraView = new CameraView(getActivity());
            FloatWindow
                    .with(AppLpds.getInstance())
                    .setView(mCameraView)
                    //设置控件宽高
                    .setWidth(AutoSizeUtils.dp2px(getActivity(), 140))
                    .setHeight(AutoSizeUtils.dp2px(getActivity(), 120))
                    //设置控件初始位置
//                                .setX(Screen.width -AutoSizeUtils.dp2px(MainActivity2.this, 300))
//                                .setY(Screen.height - AutoSizeUtils.dp2px(MainActivity2.this, 400))
                    .setMoveType(MoveType.active)
                    //桌面显示
                    .setDesktopShow(true)
                    .setViewStateListener(new ViewStateListener() {
                        @Override
                        public void onPositionUpdate(int x, int y) {
                            Log.d(TAG, "onPositionUpdate: x=" + x + " y=" + y);
                        }

                        @Override
                        public void onShow() {
                            Log.d(TAG, "onShow");
                        }

                        @Override
                        public void onHide() {
                            Log.d(TAG, "onHide");
                        }

                        @Override
                        public void onDismiss() {
                            Log.d(TAG, "onDismiss");
                        }

                        @Override
                        public void onMoveAnimStart() {
                            Log.d(TAG, "onMoveAnimStart");
                        }

                        @Override
                        public void onMoveAnimEnd() {
                            Log.d(TAG, "onMoveAnimEnd");
                        }

                        @Override
                        public void onBackToDesktop() {
                            Log.d(TAG, "onBackToDesktop");
                        }
                    })    //监听悬浮控件状态改变
                    .setPermissionListener(new PermissionListener() {
                        @Override
                        public void onSuccess() {
                            Log.d(TAG, "onSuccess");
                        }

                        @Override
                        public void onFail() {
                            Log.d(TAG, "onFail");
                        }
                    })  //监听权限申请结果
                    .setTag("camera")
                    .build();
            FloatWindow.get("camera").show();
        } else {
            FloatWindow.destroy("camera");
        }
    }

    // Fragment页面onResume函数重载
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("HomeFragment");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unbindService(connection);
        FloatWindow.destroy();
    }
}
